package com.dhecp.core.utils;

import com.dhecp.core.domain.BaseBusinessEntity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 根据属性名反射获取get和set方法赋值
 * @author DH-Xxj
 * @version 2019年11月25日
 */
public class ReflectUtils {

	/**
	 * 各方法测试（使用示例）
	 * @param args
	 * @throws Exception
	 * @author DH-Xxj
	 */
	public static void main(String[] args)throws Exception{
		//removeLine 方法示例
		System.out.println(removeLine("abg_dwr"));
		System.out.println(removeLine("ab_wr"));
		System.out.println(removeLine("abgwr"));
		System.out.println(removeLine(null));
 
		//get 方法示例
		BaseBusinessEntity businessEntity1 = new BaseBusinessEntity();
		businessEntity1.setBid("BJ-101");
		businessEntity1.setbUser("0000");
		Object ob = getGetMethod(businessEntity1, "bUser");
		System.out.println(ob);
		
		//set 方法示例
		BaseBusinessEntity businessEntity2 = new BaseBusinessEntity();
		String field2 = "bUser";
		setValue(businessEntity2, field2, "1001");
		System.out.println(businessEntity2.getbUser());
		
		//获取某个属性的类型 方法示例
		System.out.println(BaseBusinessEntity.class.getDeclaredField("bid").getType());
	
	}
	
	/**
	 * 根据属性，获取get方法
	 * @param ob 对象
	 * @param filedName 属性名
	 * @return
	 * @throws Exception
	 */
	public static Object getGetMethod(Object obj , String filedName)throws Exception{
		filedName = removeLine(filedName);
		Method[] m = obj.getClass().getMethods();
		for(int i = 0;i < m.length;i++){
			if(("get" + filedName).toLowerCase().equals(m[i].getName().toLowerCase())){
				return m[i].invoke(obj);
			}
		}
		return null;
	}
	
	/**
	 * 根据属性，拿到set方法，并把值set到对象中
	 * @param obj 对象
	 * @param fileName 需要设置值得属性
	 * @param value
	 */
	public static void setValue(Object obj,String filedName,Object value) {
		filedName = removeLine(filedName);
		Class<?> clazz = obj.getClass();
		Class<?> pclazz = null;
		Class<?> curclazz = null;
		Class<?> typeClass = null;
		Method[] methods = null;
		String methodName = "";

		//首先搜索当前类中是否存在该属性
		Field objFieldName = null;
		try {
			objFieldName = clazz.getDeclaredField(filedName);
			methods = clazz.getMethods();
			for(int i = 0;i < methods.length;i++){
				if(("set" + filedName).toLowerCase().equals(methods[i].getName().toLowerCase())){
					methodName = methods[i].getName();
				}
			}
		} catch (NoSuchFieldException e1) {
			objFieldName = null;
		} catch (SecurityException e1) {
			objFieldName = null;
		}

		//如果当前类中不存在该属性则遍历搜索其父类
		if (objFieldName == null){
			pclazz = clazz.getSuperclass();
			for (; pclazz != Object.class && objFieldName == null; pclazz = pclazz.getSuperclass()) {//向上循环  遍历父类
				try {
					objFieldName = pclazz.getDeclaredField(filedName);
					methods = pclazz.getMethods();
					for(int i = 0;i < methods.length;i++){
						if(("set" + filedName).toLowerCase().equals(methods[i].getName().toLowerCase())){
							methodName = methods[i].getName();
						}
					}
				} catch (NoSuchFieldException e1) {
					objFieldName = null;
				} catch (SecurityException e1) {
					objFieldName = null;
				}
				curclazz = pclazz;
			}			
		}
		
		if (objFieldName != null){
			typeClass = objFieldName.getType();
			try{
				Method method =  clazz.getDeclaredMethod(methodName, new Class[]{typeClass});
				method.invoke(obj, new Object[]{getClassTypeValue(typeClass, value)});
			}catch(Exception ex){
				try{
					Method method =  curclazz.getDeclaredMethod(methodName, new Class[]{typeClass});
					method.invoke(obj, new Object[]{getClassTypeValue(typeClass, value)});
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
     * 通过class类型获取获取对应类型的值
     * @param typeClass class类型
     * @param value 值
     * @return Object
     */
	private static Object getClassTypeValue(Class<?> typeClass, Object value){
        if(typeClass == int.class || typeClass == Integer.class){
            if(null == value || "".equals(value.toString())){
                return 0;
            }
            return Integer.parseInt(value.toString());
        }else if(typeClass == Date.class){
            if(null == value || "".equals(value.toString())){
                return null;
            }
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
			Date date = null;
			try {
				date = formatter.parse(value.toString());
			} catch (ParseException e) {
				try {
					date = formatter2.parse(value.toString());
				} catch (ParseException e2) {
					date = new Date();
				}
			}
            return date;
        }else if(typeClass == short.class){
            if(null == value || "".equals(value.toString())){
                return 0;
            }
            return Short.parseShort(value.toString());
        }else if(typeClass == byte.class){
            if(null == value || "".equals(value.toString())){
                return 0;
            }
            return value;
        }else if(typeClass == double.class || typeClass == Double.class){
            if(null == value || "".equals(value.toString())){
                return 0.0;
            }
            return Double.parseDouble(value.toString());
        }else if(typeClass == long.class){
            if(null == value || "".equals(value.toString())){
                return 0;
            }
            return Long.parseLong(value.toString());
        }else if(typeClass == String.class){
            if(null == value || "".equals(value.toString())){
                return "";
            }
            return value;
        }else if(typeClass == boolean.class || typeClass == Boolean.class){
            if(null == value || "".equals(value.toString()) || "1".equals(value.toString())){
                return true;
            }
            return Boolean.parseBoolean(value.toString());
        }else if(typeClass == BigDecimal.class){
            if(null == value || "".equals(value.toString())){
                return new BigDecimal(0);
            }
            return new BigDecimal(value+"");
        }else {
            return typeClass.cast(value);
        }
    }
    /**
     * 处理字符串  如：  abc_dex ---> abcDex
     * @param str
     * @return
     */
    public static  String removeLine(String str){
		if(null != str && str.contains("_")){
			int i = str.indexOf("_");
			char ch = str.charAt(i+1);
			char newCh = (ch+"").substring(0, 1).toUpperCase().toCharArray()[0];
			String newStr = str.replace(str.charAt(i+1), newCh);
			String newStr2 = newStr.replace("_", "");
			return newStr2;
		}
		return str;
	}
}
